<template>
	<view class="bai left clearfix">
		
		
		
		<view class="tim-yinse-item left clearfix" v-if="showContent && showContent.title">
			<view class="tim-image-left left clearfix relative">
				<image src="/static/images/shengyin.png" mode="aspectFill" style="width:70%;height:70%;border-radius: 50%;margin:15%;"></image>
				<view class="zmt-audio-play-box absolute" @click="setPlay('start',showContent,0)" v-if="innerAudioContextStatus==false || currentPayIndex!=0">
					<image src="/static/images/bofang.png"></image>
				</view>
				<view class="zmt-audio-play-box absolute" @click="setPlay('pause',showContent,0)" v-if="innerAudioContextStatus==true && currentPayIndex ==0">
					<image src="/static/images/zanting.png"></image>
				</view>
			</view>
			<view class="tim-text-box left clearfix">
					<view class="tim-text-left left clearfix ellipsis" v-if="editMyAudioTitle==false">
						{{showContent.title}}
					</view>
					<view class="tim-text-left left clearfix ellipsis" v-if="editMyAudioTitle==true">
						<input placeholder="请输入标题" maxlength="10" @blur="saveEditMyAudioTitle(content)" :focus="true" v-model="content.title" />
					</view>
					
					<view class="tim-text-right left" v-if="content.title!='暂无声音' && editMyAudioTitle==false" @click="editAudioTitle()">
						<uni-icons type="icon-chuangzuo2" size="15" color="#666" custom-prefix="iconfont"></uni-icons>
					</view>
					
					<view class="tim-text-right left" v-if="editMyAudioTitle==true" title="保存" @click="saveEditMyAudioTitle(content)">
						<uni-icons type="icon-baocunjilu5" size="15" color="#666" custom-prefix="iconfont"></uni-icons>
					</view>
					
					
			</view>
			<view class="tim-right right clearfix" title="复刻声音" @click="getAudioFromVideo()" v-if="content.title=='暂无声音'">
				复刻
			</view>
			
			<view class="tim-right right clearfix" title="重新复刻声音" @click="getAudioFromVideo()" v-else>
				重刻
			</view>
			
			<view class="tim-right right clearfix" v-if="cosyData && cosyData.length > 1" title="切换声音" @click="alertAudioItem()">
				<uni-icons type="icon-qiehuanx" color="#fff" custom-prefix="iconfont" size="20"></uni-icons>
			</view>
			
		</view>
		
		
		
		
		
		
		<!--切换声音弹窗-->
		<uni-popup ref="popup" type="center">
			<view class="cosy-box left clearfix">
				<view class="cosy-title left clearfix">
					<label>
						选择声音
					</label>
					<label @click="closePopup()">
						<uni-icons type="closeempty" size="20" color="#666"></uni-icons>
					</label>
				</view>
				
				<view class="cosy-contents left clearfix">
					
					
					<view class="left clearfix bai" v-if="cosyData && cosyData[0]">
					<view class="cosy-yinse-item left clearfix" v-for="(item,index) in cosyData">
						<view class="tim-image-left left clearfix relative">
							<image src="/static/images/shengyin.png" mode="aspectFill" style="width:70%;height:70%;border-radius: 50%;margin:15%;"></image>
							<view class="zmt-audio-play-box absolute" @click="setPlay('start',item,index)" v-if="innerAudioContextStatus==false || currentPayIndex!=index">
								<image src="/static/images/bofang.png"></image>
							</view>
							<view class="zmt-audio-play-box absolute" @click="setPlay('pause',item,index)" v-if="innerAudioContextStatus==true && currentPayIndex == index">
								<image src="/static/images/zanting.png"></image>
							</view>
						</view>
						<view class="tim-text-box left clearfix">
								
								<view class="tim-text-left left clearfix ellipsis" v-if="editItem && editItem._id==item._id">
									<input placeholder="请输入标题" maxlength="10" @blur="saveEditAudioItemTitle(item,index)" :focus="true" v-model="item.title" />
								</view>
								
								<view class="tim-text-left left clearfix ellipsis" v-else>
									{{item.title}}
								</view>
								
								<view class="tim-text-right left" v-if="!editItem || editItem._id!=item._id" @click="editAudioItemTitle(item,index)">
									<uni-icons type="icon-chuangzuo2" size="15" color="#666" custom-prefix="iconfont"></uni-icons>
								</view>
								
								<view class="tim-text-right left" v-if="editItem && editItem._id==item._id" title="保存" @click="saveEditAudioItemTitle(item,index)">
									<uni-icons type="icon-baocunjilu5" size="15" color="#666" custom-prefix="iconfont"></uni-icons>
								</view>
								
								
						</view>
						
						<view class="tim-right right clearfix" title="删除声音" @click="alertRemoveConfirm(item,index)" style="background:none;">
							<uni-icons type="icon-shanchu3" size="20" color="#666" custom-prefix="iconfont"></uni-icons>
						</view>
						
						<view class="tim-right right clearfix" title="选择声音" @click="getAudioFromVideo()" >
							选择
						</view>
						
					</view>
					</view>
					<view class="null-data left clearfix bai" v-else>
						暂无声音
					</view>
					
				</view>
				
			</view>
		</uni-popup>
		
		<u-modal :show="showRemove" @confirm="delCosyVoice()" @cancel="showRemove = false" title="删除确认" content='确定要删除吗' :showCancelButton="true"></u-modal>
	</view>
</template>

<style scoped>
	.null-data{width:100%;line-height:200px;text-align: center;font-size:15px;color:#999;}
	.zmt-audio-play-box image{width:15px;height:15px;margin-top:7.5px;margin-left:2px;}
	.zmt-audio-play-box{width:30px;height:30px;background:rgba(0, 0, 0, 0.2);z-index:30;text-align: center;line-height:30px;border-radius: 50%;left:10px;top:10px;cursor:pointer;}
	.cosy-yinse-item{width:96%;height:80px;margin-left:2%;background-color: #fff;border-radius: 8px;box-shadow: rgba(0, 0, 0, 0.15) 0px 0px 4px 1px;margin-top:10px;}
	.cosy-button{width:70%;margin-left:15%;height:40px;line-height:40px;background-image: linear-gradient(90deg, #4287fe, #298bfe 25%, #0f8ffd 51%, #25b4c1);color:#fff;text-align: center;border-radius: 20px;margin-top:20px;cursor:pointer;}
	.cosy-contents{width:90%;margin-left:5%;height:500px;overflow: auto;margin-top:20px;}
	.cosy-title label:last-child{float:right;margin-right:10px;line-height:40px;height:40px;cursor:pointer;}
	.cosy-title label:first-child{float:left;margin-left:10px;line-height:40px;height:40px;font-size:14px;font-weight:500;color:#333;}
	.cosy-title{width:100%;height:40px;line-height:40px;}
	.cosy-box{width:400px;height:550px;background:#fff;border-radius: 10px;}
	.tim-text-right{line-height:60px;margin-left:20px;margin-top:10px;cursor:pointer;}
	.tim-text-left{line-height:40px;font-size:14px;width:calc(100% - 50px);}
	.tim-text-left input{width:94%;line-height:25px;height:25px;font-size:14px;border-bottom:1px solid #ddd;margin-top:7.5px;padding-left:3px;}
	.tim-right{width:50px;height:30px;margin-top:10px;line-height:30px;margin-right:10px;cursor:pointer;font-size:12px;margin-top:26px;text-align:center;background-image: linear-gradient(90deg, #4287fe, #298bfe 25%, #0f8ffd 51%, #25b4c1);color:#fff;border-radius: 15px;cursor:pointer;}
	.tim-text-box text:last-child{color:#999;}
	.tim-text-box text:first-child{font-weight:400;}
	.tim-text-box text{width:100%;float:left;line-height:20px;font-size:12px;}
	.tim-text-box{width:40%;height:40px;margin-top:20px;}
	.tim-image-left{width:50px;height:50px;border:1px solid #eee;margin:15px;border-radius: 50%;margin-right:10px;}
	.tim-yinse-item{width:100%;height:80px;background-color: #fff;border-radius: 8px;box-shadow: rgba(0, 0, 0, 0.15) 0px 0px 4px 1px;}
</style>

<script>
var aliyun = uniCloud.importObject('aliyun',{customUI:true});
var db = uniCloud.database();
	export default {
		name:"cosy-voice",
		data() {
			return {
				innerAudioContext:null,
				innerAudioContextStatus:false,
				userinfo:{},
				content:{},
				editMyAudioTitle:false,
				cosyData:[],
				editItem:null,
				currentPayIndex:null,
				removeItem:null,
				removeIndex:null,
				showRemove:false
			};
		},
		mounted() {
			var that = this;
			uni.getStorage({
				key:'login-userinfo',
				success:function(res){
					var userinfo = res.data;
					if(userinfo && userinfo._id){
						that.userinfo = userinfo;
						//查询出5条复刻的声音
						that.getCosyVoice(userinfo._id);
					}else{
						uni.navigateTo({
							url: '/pages/index/index'
						});
					}
				},
				fail() {
					uni.navigateTo({
						url: '/pages/index/index'
					});
				}
			});
		},
		props:{
			video:{
				type:Object,
				default:{}
			},
			showContent:{
				type:Object,
				default:{}
			}
		},
		watch:{
			"showContent"(val){
				this.content = val;
			}
		},
		methods:{
			//弹出删除确认
			alertRemoveConfirm(item,index){
				this.showRemove = true;
				this.removeItem = item;
				this.removeIndex = index;
			},
			//关闭弹窗
			closePopup(){
				if(this.innerAudioContext){
					this.innerAudioContext.pause();
					this.innerAudioContext = null;
					this.innerAudioContextStatus = false;
				}
				this.$refs.popup.close();
			},
			//播放/暂停
			setPlay(status,audio,index){
				var that = this;
				this.currentPayIndex = index;
				if(status == 'start' && !that.innerAudioContext){
					this.initInnerAudioContext(audio);//再次检测音频是否被初始化
					that.playAudio(that.innerAudioContext);
				}else if((status == 'start' && that.innerAudioContext) || index != this.currentPayIndex){
					this.initInnerAudioContext(audio,true);//再次检测音频是否被初始化
					that.playAudio(that.innerAudioContext);
				}else if(status == 'start' && that.innerAudioContext){
					that.playAudio(that.innerAudioContext);
				}else if(status == 'pause' && that.innerAudioContext){
					that.pauseAudio(that.innerAudioContext);
				}
				
				//如果播放结束，则终止播放，更改播放按钮状态
				that.innerAudioContext.onEnded(()=>{
					that.$emit('onEnded',true);
					that.destroyInnerAudioContext();
				});
				that.innerAudioContext.onTimeUpdate(()=> {
					var currentTime = Math.ceil(that.innerAudioContext.currentTime);
					if(currentTime > 0){
						that.$emit('onTimeUpdate',that.innerAudioContext.currentTime);
						that.currentTime = this.convertSecondsToMinutesAndSeconds(currentTime);
						
						//计算出当前进度条播放进度
						that.currentProgress = Math.ceil((currentTime/Math.ceil(this.innerAudioContext.duration)) * 100);
					}
					
				});
			},
			//开始播放
			playAudio(innerAudioContext){
				var that = this;
				innerAudioContext.play();
				innerAudioContext.onPlay(() => {
				  that.$emit('onPlay',true);
				  that.innerAudioContextStatus = true;
				});
			},
			//暂停播放
			pauseAudio(innerAudioContext){
				var that = this;
				innerAudioContext.pause();
				innerAudioContext.onPause(() => {
				  that.$emit('onPause',true);
				  that.innerAudioContextStatus = false;
				});
			},
			//销毁播放事件
			destroyInnerAudioContext(){
				this.innerAudioContext.stop();
				this.innerAudioContextStatus = false;
				//销毁播放事件
				this.innerAudioContext.destroy();
				this.innerAudioContext = null;
			},
			//初始化状态并获取总播放时长
			initInnerAudioContext(audio,init){
				console.log('audio',audio);
				if(!this.innerAudioContext || init == true){
					this.innerAudioContext = uni.createInnerAudioContext(); 
					this.innerAudioContext.src = audio.audio_url?audio.audio_url:audio.audio_src;//音频地址
					this.innerAudioContext.loop = audio.loop?audio.loop:false;//循环播放
				}
				this.innerAudioContext.onCanplay(()=>{
					this.duration = this.convertSecondsToMinutesAndSeconds(parseInt(this.innerAudioContext.duration));
				});
			},
			//将秒数转化为分钟：秒
			convertSecondsToMinutesAndSeconds(seconds) {
			    var minutes = Math.floor(seconds / 60);
				if(minutes < 10){
					minutes = '0' + minutes;
				}
			    var remainingSeconds = seconds % 60;
				if(remainingSeconds < 10){ 
					remainingSeconds = '0' + remainingSeconds;
				}
				return minutes+':'+remainingSeconds;
			},
			//保存复刻列表中的标题
			saveEditAudioItemTitle(item,index){
				var id = item._id;
				if(id){
					var data = item;
					delete data._id;
					db.collection('digital_history').where({_id:id}).update(data).then(res=>{
						data._id = id;
						this.cosyData[index] = data;
						this.editItem = null;
						uni.showToast({
							title:'保存成功',
							icon:'none',
							duration:2000
						})
					});
				}
				
			},
			//点击复刻声音列表中的修改标题
			editAudioItemTitle(item){
				this.editItem = item;
			},
			//查询出5条复刻的声音
			getCosyVoice(uid){
				db.collection('digital_history').where({uid:uid,type:'audio-fuke'}).orderBy('_id desc').limit(5).get().then(res=>{
					this.cosyData = res.result.data;
				});
			},
			//切换声音
			alertAudioItem(){
				if(this.innerAudioContext){
					this.innerAudioContext.pause();
					this.innerAudioContext = null;
					this.innerAudioContextStatus = false;
				}
				this.$refs.popup.open();
			},
			editAudioTitle(){
				this.editMyAudioTitle = true;
				this.editFocus = true;
			},
			//点击保存以后
			saveEditMyAudioTitle(content){
				this.editMyAudioTitle = false;
				this.editFocus = false;
				var id = content._id;
				if(id){
					delete content._id;
					db.collection('digital_history').where({_id:content._id}).update(content).then(res=>{
						content._id = id;
						this.content = content;
						uni.showToast({
							title:'保存成功',
							icon:'success',
							duration:2000
						})
					}).catch(err=>{
						console.log('宝墩失败',err);
					});
				}
				
			},
			//复核声音配音
			async getAudioFromVideo(){
				var that = this;
				var videoSrc = that.video.url;//视频链接
				if(videoSrc){
					//如果复刻的声音大于了5个，将会将之前的复刻声音删除
					if(this.cosyData && this.cosyData.length >=5){
						that.delCosyVoice(this.cosyData[4]);
					}
					this.$emit('setContent',{show:true,message:'音频提取中···'});
					uni.request({
					    url: 'http://ai.mofang360.com/getAudioFromVideo.php',
					    data: {
					        token: 'sk-986abea2283641f9b6f0573f71ff0f44',
							data:{
								videoSrc:videoSrc
							}
					    },
						method:"POST",
					    header: {
					        'Content-Type': 'application/json'
					    },
					    success: (res) => {
							console.log('音频连接',res);
							that.$emit('success',res.data);
					        this.text = 'request success';
					    },
						fail(err) {
							console.log('提取声音错误',err);
						}
					});
				}else{
					uni.showToast({
						title:'请上传一段带清晰声音的视频',
						icon:'none'
					})
				}
				
				
			},
			//删除音色
			delCosyVoice(cosy,index){
				if(!cosy){
					cosy = this.removeItem;
				}
				if(!index && index!=0){
					index = this.removeIndex;
				}
				if(cosy && cosy._id){
					var data = {
						"model": "voice-enrollment",
						"input": {
							"action": "delete_voice",
							"voice_id": cosy.voice_name
						}
					}
					//从阿里云删除音色
					aliyun.delCosyVoice(data);
					//从数据库删除音色
					if(index || index == 0){
						db.collection('digital_history').where({_id:cosy._id}).remove().then(res=>{
							this.showRemove = false;
							uni.showToast({
								title:'删除成功',
								icon:'none',
								duration:2000
							})
							this.cosyData.splice(index,1);
						})
					}else{
						db.collection('digital_history').where({_id:cosy._id}).remove();
					}
					
				}
				
			}
		}
	}
</script>
